/**
 * 
 */
package com.munoor.dalai.client.presenter;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.munoor.dalai.client.Dalai;
import com.munoor.dalai.client.event.LoginEvent;
import com.munoor.dalai.client.event.LoginEventHandler;

/**
 * @author Osho
 * 
 */
public class UserBadgePresenter implements Presenter {
	private final SimpleEventBus eventBus;
	private final Display display;

	public interface Display {
		HasClickHandlers getLogoutLink();

		HasText getUsernameLabel();

		Widget asWidget();
	}

	public UserBadgePresenter(SimpleEventBus eventBus, Display display) {
		this.eventBus = eventBus;
		this.display = display;
	}

	public void bind() {
		this.display.getLogoutLink().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				doLogout();
			}
		});

		// Listen to login events
		eventBus.addHandler(LoginEvent.TYPE, new LoginEventHandler() {
			@Override
			public void onLogin(LoginEvent event) {
				doLogin();
			}
		});
	}

	private void doLogout() {
		GWT.log("Log out");
	}

	private void doLogin() {
		if (Dalai.get().getUser().getUsername() != null)
			UserBadgePresenter.this.display.getUsernameLabel().setText(Dalai.get().getUser().getUsername());
		else
			UserBadgePresenter.this.display.getUsernameLabel().setText("Login first");
	}

	public void go(final HasWidgets container) {
		container.clear();
		container.add(display.asWidget());
		display.getUsernameLabel().setText(Dalai.get().getUser().getUsername());
		bind();
	}
}
